import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import {
  CanActivateChild, CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
}                           from '@angular/router';
import 'rxjs/add/operator/toPromise';

import { GlobalState } from 'app/global.state';

@Injectable()
export class PagesGuard implements CanActivateChild, CanActivate {
    private authorizationUrl: string = '/water/auth';

    constructor(private _state: GlobalState, private _router: Router, private _http: Http) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        return this.checkAuthorization(state.url);
    }

    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        return this.checkAuthorization(state.url);
    }

    private checkAuthorization(url: string) {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this._http.post(this.authorizationUrl, {url}, options)
            .toPromise()
            .then(resp => {
                let body = resp.json();
              let canActivate: boolean = body.status === 'success' ? true : false;
                if (!canActivate) {
                    this._router.navigateByUrl(body.data.url);
                }
                return canActivate;
            });
    }
}
